package com.quanyan.pay.service.impl;

import com.quanyan.alipay.config.AlipayConfig;
import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.encrypt.AESCoder;
import com.quanyan.common.encrypt.Coder;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.pay.entity.AlipayAccount;
import com.quanyan.pay.entity.AlipayAccountExample;
import com.quanyan.pay.entity.WeichatAccount;
import com.quanyan.pay.entity.WeichatAccountExample;
import com.quanyan.pay.mapper.AlipayAccountMapper;
import com.quanyan.pay.mapper.WeichatAccountMapper;
import com.quanyan.pay.service.AccountService;
import com.quanyan.pay.vo.response.PayAccount;
import com.quanyan.pay.web.request.ReqAlipayAccount;
import com.quanyan.pay.web.request.ReqWeichatAccount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author songzj
 * @date 16/5/30-16:52
 */
@Service("accountService")
public class AccounServiceImpl implements AccountService {

    @Autowired
    private AlipayAccountMapper alipayAccountMapper;

    @Autowired
    private WeichatAccountMapper weichatAccountMapper;

    @Override
    public APIResponse<AlipayAccount> insertOrUpdateAlipayAccount(APIRequest<ReqAlipayAccount> alipayAccountAPIRequest) {

        ReqAlipayAccount reqAlipayAccount = alipayAccountAPIRequest.getData();
        AlipayAccount alipayAccount = new AlipayAccount();
        alipayAccount.setPartner(reqAlipayAccount.getPartner());
        //对关键信息加密
        alipayAccount.setPrivateKey(AESCoder.encodeContent(reqAlipayAccount.getPrivateKey()));
        alipayAccount.setPublicKey(AESCoder.encodeContent(reqAlipayAccount.getPublicKey()));
        alipayAccount.setAliKey(AESCoder.encodeContent(reqAlipayAccount.getAliKey()));
        alipayAccount.setSeller(reqAlipayAccount.getSeller());
        alipayAccount.setStatus(reqAlipayAccount.getStatus());
        alipayAccount.setId(reqAlipayAccount.getId());
        alipayAccount.setAppId(reqAlipayAccount.getAppId());
        AlipayAccountExample alipayAccountExample = new AlipayAccountExample();
        AlipayAccountExample.Criteria criteria = alipayAccountExample.createCriteria();
        criteria.andPartnerEqualTo(reqAlipayAccount.getPartner());
        int count = this.alipayAccountMapper.countByExample(alipayAccountExample);

        if (alipayAccount.getId() == null && count == 0) {
            alipayAccount.setInputCharset(Coder.UTF_8);
            alipayAccount.setSignType("RSA");
            alipayAccount.setStatus(Constants.IS_ENABLE_FALSE);
            this.alipayAccountMapper.insertSelective(alipayAccount);
        } else {
            AlipayAccount account = this.alipayAccountMapper.selectByExample(alipayAccountExample).get(0);
            alipayAccount.setStatus(reqAlipayAccount.getStatus());
            alipayAccount.setId(account.getId());
            this.alipayAccountMapper.updateByPrimaryKeySelective(alipayAccount);
        }
        return APIResponse.returnSuccess(alipayAccount);
    }

    @Override
    public APIResponse<PageObj<List<AlipayAccount>>> selectAlipayAccountListByProperty(APIRequest<ReqAlipayAccount> apiRequest) {
        ReqAlipayAccount reqAlipayAccount = apiRequest.getData();

        AlipayAccountExample alipayAccountExample = new AlipayAccountExample();
        AlipayAccountExample.Criteria aliCriteria = alipayAccountExample.createCriteria();
        if (!StringUtil.isBlankOrNull(reqAlipayAccount.getPartner())) {
            aliCriteria.andPartnerEqualTo(reqAlipayAccount.getPartner());
        }

        if (!StringUtil.isBlankOrNull(reqAlipayAccount.getSeller())) {
            aliCriteria.andSellerEqualTo(reqAlipayAccount.getSeller());
        }

        if (reqAlipayAccount.getStatus() != null) {
            aliCriteria.andStatusEqualTo(reqAlipayAccount.getStatus());
        }

        int count = this.alipayAccountMapper.countByExample(alipayAccountExample);
        Page page = Page.createPage(count, reqAlipayAccount.getPageNo(), reqAlipayAccount.getPageSize());
        alipayAccountExample.setPage(page);
        List<AlipayAccount> alipayAccounts = this.alipayAccountMapper.selectByExample(alipayAccountExample);
        PageObj<List<AlipayAccount>> pageObj = PageObj.create(count, reqAlipayAccount.getPageNo(), reqAlipayAccount.getPageSize(), alipayAccounts);
        return APIResponse.returnSuccess(pageObj);
    }


    @Override
    public AlipayConfig selectAlipayConfigBySellerIdAndEmail(String sellerId, String sellerEmail) {
        APIRequest<ReqAlipayAccount> apiRequest = new APIRequest();
        ReqAlipayAccount reqAlipayAccount = new ReqAlipayAccount();
        reqAlipayAccount.setPartner(sellerId);
        reqAlipayAccount.setSeller(sellerEmail);
        apiRequest.setData(reqAlipayAccount);
        APIResponse<AlipayAccount> alipayAccountAPIResponse = this.selectAlipayAccountByProperty(apiRequest);
        AlipayAccount alipayAccount = alipayAccountAPIResponse.getData();
        return new AlipayConfig.Builder()
                .setSeller(alipayAccount.getSeller())
                .setPrivate_key(alipayAccount.getPrivateKey())
                .setPartner(alipayAccount.getPartner())
                .setKey(alipayAccount.getAliKey())
                .setOpen_public_key(alipayAccount.getOpenPublicKey())
                .setAli_public_key(alipayAccount.getPublicKey()).build();
    }

    @Override
    public PayAccount selectAllAccount() {
        PayAccount payAccount = new PayAccount();
        //获取所有启用的微信账号
        WeichatAccountExample weichatAccountExample = new WeichatAccountExample();
        weichatAccountExample.createCriteria().andStatusEqualTo((byte)1);
        List<WeichatAccount> weichatAccountList = weichatAccountMapper.selectByExample(weichatAccountExample);
        for(WeichatAccount weichatAccount : weichatAccountList){
            weichatAccount.setWxKey(AESCoder.decodeContent(weichatAccount.getWxKey()));
            weichatAccount.setSecurityKey(AESCoder.decodeContent(weichatAccount.getSecurityKey()));
            weichatAccount.setCertPasswd(AESCoder.decodeContent(weichatAccount.getCertPasswd()));
        }
        //获取所有启用的支付宝账号
        AlipayAccountExample alipayAccountExample = new AlipayAccountExample();
        alipayAccountExample.createCriteria().andStatusEqualTo((byte)1);
        List<AlipayAccount> alipayAccountList = alipayAccountMapper.selectByExample(alipayAccountExample);
        for(AlipayAccount alipayAccount : alipayAccountList){
            alipayAccount.setPrivateKey(AESCoder.decodeContent(alipayAccount.getPrivateKey()));
            alipayAccount.setPublicKey(AESCoder.decodeContent(alipayAccount.getPublicKey()));
            alipayAccount.setAliKey(AESCoder.decodeContent(alipayAccount.getAliKey()));
            alipayAccount.setOpenPublicKey(AESCoder.decodeContent(alipayAccount.getOpenPublicKey()));
        }
        payAccount.setAlipayAccountList(alipayAccountList);
        payAccount.setWxAccountList(weichatAccountList);
        return payAccount;
    }

    @Override
    public APIResponse<AlipayAccount> selectAlipayAccountByProperty(APIRequest<ReqAlipayAccount> apiRequest) {
        ReqAlipayAccount reqAlipayAccount = apiRequest.getData();

        AlipayAccount alipayAccount = null;
        if (reqAlipayAccount.getId() != null) {
            alipayAccount = this.alipayAccountMapper.selectByPrimaryKey(reqAlipayAccount.getId());
        } else {
            AlipayAccountExample alipayAccountExample = new AlipayAccountExample();
            AlipayAccountExample.Criteria aliCriteria = alipayAccountExample.createCriteria();
            if (!StringUtil.isBlankOrNull(reqAlipayAccount.getPartner())) {
                aliCriteria.andPartnerEqualTo(reqAlipayAccount.getPartner());
            }

            if (!StringUtil.isBlankOrNull(reqAlipayAccount.getSeller())) {
                aliCriteria.andSellerEqualTo(reqAlipayAccount.getSeller());
            }

            List<AlipayAccount> alipayAccounts = this.alipayAccountMapper.selectByExample(alipayAccountExample);
            if (alipayAccounts == null || alipayAccounts.size() == 0) {
                throw new BizException(ApiResponseEnum.RECORD_DO_NOT_EXISTS);
            }
            alipayAccount = alipayAccounts.get(0);
        }

        alipayAccount.setPrivateKey(AESCoder.decodeContent(alipayAccount.getPrivateKey()));
        alipayAccount.setPublicKey(AESCoder.decodeContent(alipayAccount.getPublicKey()));
        alipayAccount.setAliKey(AESCoder.decodeContent(alipayAccount.getAliKey()));
        alipayAccount.setOpenPublicKey(AESCoder.decodeContent(alipayAccount.getOpenPublicKey()));
        return APIResponse.returnSuccess(alipayAccount);
    }

    @Override
    public APIResponse<WeichatAccount> insertOrUpdateWeichatAccount(APIRequest<ReqWeichatAccount> reqWeichatAccount) {

        WeichatAccount weichatAccount = new WeichatAccount();
        weichatAccount.setId(reqWeichatAccount.getData().getId());
        weichatAccount.setAppId(reqWeichatAccount.getData().getAppId());
        weichatAccount.setMchId(reqWeichatAccount.getData().getMchId());
        weichatAccount.setSubMchId(reqWeichatAccount.getData().getSubMchId());

        weichatAccount.setWxKey(AESCoder.encodeContent(reqWeichatAccount.getData().getWxKey()));
        if (!StringUtil.isBlankOrNull(reqWeichatAccount.getData().getSecurityKey())) {
            weichatAccount.setSecurityKey(AESCoder.encodeContent(reqWeichatAccount.getData().getSecurityKey()));
        }

        weichatAccount.setCertData(reqWeichatAccount.getData().getCertLocationPath());
        weichatAccount.setCertPasswd(AESCoder.encodeContent(reqWeichatAccount.getData().getCertPassword()));
        weichatAccount.setOpenId(reqWeichatAccount.getData().getOpenId());
        if (reqWeichatAccount.getData().getId() == null) {
            weichatAccount.setStatus(Constants.IS_ENABLE_TRUE);
            this.weichatAccountMapper.insertSelective(weichatAccount);
        } else {
            weichatAccount.setStatus(reqWeichatAccount.getData().getStatus());
            this.weichatAccountMapper.updateByPrimaryKeySelective(weichatAccount);
        }
        return APIResponse.returnSuccess(weichatAccount);
    }

    @Override
    public APIResponse<PageObj<List<WeichatAccount>>> selectWeichatAccountListByProperty(APIRequest<ReqWeichatAccount> reqWeichatAccountApi) {
        ReqWeichatAccount reqWeichatAccount = reqWeichatAccountApi.getData();

        WeichatAccountExample weichatAccountExample = new WeichatAccountExample();
        WeichatAccountExample.Criteria criteria = weichatAccountExample.createCriteria();
        if (!StringUtil.isBlankOrNull(reqWeichatAccount.getAppId())) {
            criteria.andAppIdEqualTo(reqWeichatAccount.getAppId());
        }
        if (!StringUtil.isBlankOrNull(reqWeichatAccount.getMchId())) {
            criteria.andMchIdEqualTo(reqWeichatAccount.getMchId());
        }
        if (!StringUtil.isBlankOrNull(reqWeichatAccount.getOpenId())) {
            criteria.andOpenIdEqualTo(reqWeichatAccount.getOpenId());
        }
        if (reqWeichatAccount.getStatus() != null) {
            criteria.andStatusEqualTo(reqWeichatAccount.getStatus());
        }
        int count = this.weichatAccountMapper.countByExample(weichatAccountExample);
        Page page = Page.createPage(count, reqWeichatAccount.getPageNo(), reqWeichatAccount.getPageSize());
        weichatAccountExample.setPage(page);
        List<WeichatAccount> weichatAccounts = this.weichatAccountMapper.selectByExample(weichatAccountExample);
        PageObj<List<WeichatAccount>> pageObj = PageObj.create(weichatAccounts, page);
        return APIResponse.returnSuccess(pageObj);
    }

    @Override
    public APIResponse<WeichatAccount> selectWeichatAccountByProperty(APIRequest<ReqWeichatAccount> reqWeichatAccountApi) {

        ReqWeichatAccount reqWeichatAccount = reqWeichatAccountApi.getData();

        if (reqWeichatAccount.getId() != null) {
            WeichatAccount weichatAccount = this.weichatAccountMapper.selectByPrimaryKey(reqWeichatAccount.getId());
            weichatAccount.setWxKey(AESCoder.decodeContent(weichatAccount.getWxKey()));
            weichatAccount.setSecurityKey(AESCoder.decodeContent(weichatAccount.getSecurityKey()));
            weichatAccount.setCertPasswd(AESCoder.decodeContent(weichatAccount.getCertPasswd()));
            return APIResponse.returnSuccess(weichatAccount);
        }

        WeichatAccountExample weichatAccountExample = new WeichatAccountExample();
        WeichatAccountExample.Criteria criteria = weichatAccountExample.createCriteria();
        if (!StringUtil.isBlankOrNull(reqWeichatAccount.getAppId())) {
            criteria.andAppIdEqualTo(reqWeichatAccount.getAppId());
        }
        if (!StringUtil.isBlankOrNull(reqWeichatAccount.getMchId())) {
            criteria.andMchIdEqualTo(reqWeichatAccount.getMchId());
        }
        if (!StringUtil.isBlankOrNull(reqWeichatAccount.getOpenId())) {
            criteria.andOpenIdEqualTo(reqWeichatAccount.getOpenId());
        }

        List<WeichatAccount> weichatAccounts = this.weichatAccountMapper.selectByExampleWithBLOBs(weichatAccountExample);
        if (weichatAccounts == null || weichatAccounts.size() == 0) {
            throw new BizException(ApiResponseEnum.RECORD_DO_NOT_EXISTS);
        }
        return APIResponse.returnSuccess(weichatAccounts.get(0));
    }


}
